package com.ncs.cns.business.util;


import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;


public class DateUtil {
	public static final String PROP_NAME_CURRENT_YEAR = "current.year";
	//private static Map<String,SimpleDateFormat> formatPool = new HashMap<String,SimpleDateFormat>();
	//private static Log logger = LogFactory.getLog(DateUtil.class.getName());
	 /**
     * "JAN" to represent January
     */
    public static final String MTH_JAN = "Jan";

    /**
     * "FEB" to represent February
     */
    public static final String MTH_FEB = "Feb";
	
    /**
     * "MAR" to represent March
     */
    public static final String MTH_MAR = "Mar";

    /**
     * "APR" to represent April
     */
    public static final String MTH_APR = "Apr";

    /**
     * "MAY" to represent May
     */
    public static final String MTH_MAY = "May";

    /**
     * "JUNE" to represent June
     */
    public static final String MTH_JUN = "Jun";

    /**
     * "JUL" to represent July
     */
    public static final String MTH_JUL = "Jul";

    /**
     * "AUG" to represent August
     */
    public static final String MTH_AUG = "Aug";

    /**
     * "SEP" to represent September
     */
    public static final String MTH_SEP = "Sep";

    /**
     * "OCT" to represent October
     */
    public static final String MTH_OCT = "Oct";

    /**
     * "NOV" to represent November
     */
    public static final String MTH_NOV = "Nov";

    /**
     * "DEC" to represent December
     */
    public static final String MTH_DEC = "Dec";
    public static final String MMDDHH = "MM dd hh mm";
    public static final String yyyy_MM_dd ="yyyy-MM-dd";
    public static final String MMddyyyy ="MM/dd/yyyy";
    public static final String yyyy_MM_dd_HH_mm_ss ="yyyy-MM-dd HH:mm:ss";
    public static final String MMddyyyyHHmmss ="MM/dd/yyyy HH:mm:ss";
    
    public static final String yyyy="yyyy";//add by xinfu 20111004
    
	private static SimpleDateFormat inputDateFormat = new SimpleDateFormat("dd/MM/yyyy");
	private static SimpleDateFormat inputDateFormatForReport = new SimpleDateFormat("MM/dd/yyyy");
    private static SimpleDateFormat timeFormatSimple = new SimpleDateFormat("yyyyMMdd-HHmmss");
    private static SimpleDateFormat dtFormatSimpleFull = new SimpleDateFormat("yyyyMMddHHmmss");
    private static SimpleDateFormat timeFormatIncludeSeconds = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    private static SimpleDateFormat timeFormatIncludeSeconds_mm_dd_yyyy = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

    private static SimpleDateFormat timeFormatAMPM = new SimpleDateFormat("dd/MM/yyyy h:mm a");
    private static SimpleDateFormat timeFormatAMPMIncludeSeconds = new SimpleDateFormat("dd/MM/yyyy h:mm:ss a");
    private static SimpleDateFormat timeFormatNoSeconds = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    private static SimpleDateFormat dateFormat_yyyy_MM_dd= new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat dateFormat_yyyy_MM_dd_HH_mm_ss= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static String DTyyyyMMdd ="yyyyMMdd";
    private static String TMSyyyyMMddHHmmss ="yyyyMMddHHmmss";
    private static String timezone = "Asia/Singapore";
    
    
    //add by wen hao for simple date format multi-thread safe
    private static String inputDateFormatString = "yyyy-MM-dd";
    //add by wen hao for simple date format multi-thread safe
    
    
   
    public static Timestamp convertDateToTimestamp(Date date){
    	if(date!=null)
    		return new Timestamp(date.getTime());
    	return null;
    }
//    public static String dateToStr(Date date,String format)
//    {
//        if (date == null)
//            return "";
//        return getDateFormat(format).format(date);
//    }
//    public static String dateToStr(Timestamp date,String format)
//    {
//        if (date == null)
//            return "";
//        return getDateFormat(format).format(date);
//    }
//    public static String dateToStr(Date date)
//    {
//        return dateToStr(date,DTyyyyMMdd);
//    }
//    
//    public static String dateToStrDTyyyy_MM_dd(Date date)
//    {
//        return dateToStr(date,yyyy_MM_dd);
//    }
    
//    public static String dateToStr(Timestamp date)
//    {   
//        return dateToStr(date,TMSyyyyMMddHHmmss);
//    }
    public static java.util.Date inputStrToDate(String inputStr)
    {
    	if (inputStr == null || inputStr.trim().equals("")) {
			return null;
		}
		Date result = null;
		try {
			result = inputDateFormat.parse(inputStr);
		} catch (Exception e) {
//			if (logger.isWarnEnabled()) {
//				logger.warn("Failed to parse datetime (date=" + inputStr
//						+ ", pattern=" + "dd/MM/yyyy", e);
//			}
		}
			
     	return result;
    }
    
    //add by xinfu 04/25/2012
    public static java.util.Date inputStrToDateFormat_MM_dd_yyyy(String inputStr)
    {
    	if (inputStr == null || inputStr.trim().equals("")) {
			return null;
		}
		Date result = null;
		try {
			result = inputDateFormatForReport.parse(inputStr);
		} catch (Exception e) {
//			if (logger.isWarnEnabled()) {
//				logger.warn("Failed to parse datetime (date=" + inputStr
//						+ ", pattern=" + "MM/dd/yyyy", e);
//			}
		}
			
     	return result;
    }

	public static Date inputStrAppendTimeToDate(String inputStrAppendTime) {
		if (inputStrAppendTime == null || inputStrAppendTime.trim().equals("")) {
			return null;
		}
		Date result = null;
		try {
			result = timeFormatIncludeSeconds.parse(inputStrAppendTime);
		} catch (Exception e) {
//			if (logger.isWarnEnabled()) {
//				logger.warn("Failed to parse datetime (date=" + inputStrAppendTime
//						+ ", pattern=" + "dd/MM/yyyy HH:mm:ss", e);
//			}
		}
			
     	return result;
	}
	
	public static Date inputStrAppendTimeToDate_mm_dd_yyyy(String inputStrAppendTime) {
		if (inputStrAppendTime == null || inputStrAppendTime.trim().equals("")) {
			return null;
		}
		Date result = null;
		try {
			result = timeFormatIncludeSeconds_mm_dd_yyyy.parse(inputStrAppendTime);
		} catch (Exception e) {
//			if (logger.isWarnEnabled()) {
//				logger.warn("Failed to parse datetime (date=" + inputStrAppendTime
//						+ ", pattern=" + "MM/dd/yyyy HH:mm:ss", e);
//			}
		}
			
     	return result;
	}
	
/*******add by xuefeng*/
   public static String dateToInputStr_yyyy_MM_dd(java.util.Date date){
       if (date == null)  
           return null;
      // replaced with a new API to make the multi-thread safe .
      // return dateFormat_yyyy_MM_dd.format(date);
       return SafeSimpleDateFormat.getInstance().format(inputDateFormatString, date, inputDateFormatString);
   }
   
   
   public static String dateToInputStr_yyyy_MM_dd_HH_mm_ss(java.util.Date date){
       if (date == null)  
           return null;
      // replaced with a new API to make the multi-thread safe .
      // return dateFormat_yyyy_MM_dd.format(date);
       return SafeSimpleDateFormat.getInstance().format(yyyy_MM_dd_HH_mm_ss, date, yyyy_MM_dd_HH_mm_ss);
   }
   
   //add by wen hao  10 Dec 2012
   
   public static String dateToInputStrSpecifiedFormat(String formnat,java.util.Date date){
       if (date == null)  
           return null;
       return SafeSimpleDateFormat.getInstance().format(formnat, date, formnat);
   }
   
 //add by wen hao  10 Dec 2012
   
   
   
   
   
   public static String formatToFormat(String fromFormat,String toFormat,String dateStr){
	  
		 SimpleDateFormat fromFt= new SimpleDateFormat(fromFormat);
		 SimpleDateFormat toFt= new SimpleDateFormat(toFormat);
		 Date date=null;
		try {
			date = fromFt.parse(dateStr);
		} catch (ParseException e) {
//			logger.warn("Failed to parse datetime (date=" + dateStr
//					+ ", pattern=" + fromFormat, e);
//			return null;
		}
		dateStr=toFt.format(date);
		//added by xue feng start
		
		
		//added by xue feng end
	    return DateUtil.formatDateString(dateStr);
   }
   
   public static String dateToFormat(String format, java.util.Date date){
       if (date == null){
    	   return null ;
       }
       return new SimpleDateFormat(format).format(date);
   }
/*********end*****/
   
   
   public static java.util.Date inputStrToDateYYYY_MM_DD_HH_MM_SS(String inputStr)
   {
		if (inputStr == null || inputStr.trim().equals("")) {
			return null;
		}
		Date result = null;
		try {
			result = dateFormat_yyyy_MM_dd_HH_mm_ss.parse(inputStr);
		} catch (Exception e) {
//			if (logger.isWarnEnabled()) {
//				logger.warn("Failed to parse datetime (date=" + inputStr
//						+ ", pattern=" + "dd/MM/yyyy h:mm a", e);
//			}
		}
			
    	return result;
   }
   
	
	public static java.util.Date inputStrToDateAMPM(String inputStr)
    {
		if (inputStr == null || inputStr.trim().equals("")) {
			return null;
		}
		Date result = null;
		try {
			result = timeFormatAMPM.parse(inputStr);
		} catch (Exception e) {
//			if (logger.isWarnEnabled()) {
//				logger.warn("Failed to parse datetime (date=" + inputStr
//						+ ", pattern=" + "dd/MM/yyyy h:mm a", e);
//			}
		}
			
     	return result;
    }
	
	public static java.util.Date inputStrToDateAMPMIncludeSeconds(String inputStr)
    {
		if (inputStr == null || inputStr.trim().equals("")) {
			return null;
		}
		
		Date result = null;
		try {
			result = timeFormatAMPMIncludeSeconds.parse(inputStr);
		} catch (Exception e) {
//			if (logger.isWarnEnabled()) {
//				logger.warn("Failed to parse datetime (date=" + inputStr
//						+ ", pattern=" + "dd/MM/yyyy h:mm:ss a", e);
//			}
		}
			
     	return result;
    }
    public static String dateToInputStr(java.util.Date date)
    {
        if (date == null)  
            return "";
        return inputDateFormat.format(date);
    }
    
    public static String dateToInputStrForReport(java.util.Date date)
    {
        if (date == null)  
            return "";
        return inputDateFormatForReport.format(date);
    }
    
    public static String dateToInputStrAppendTime(java.util.Date date)
    {
        if (date == null)
            return "";
        return timeFormatIncludeSeconds.format(date);
    }
    
    public static String dateToInputStrAppendTime_mm_dd_yyyy(java.util.Date date)
    {
        if (date == null)
            return "";
        return timeFormatIncludeSeconds_mm_dd_yyyy.format(date);
    }
    
    
    
    
    public static String dateToDateTimeSimpleFull(java.util.Date date)
    {
        if (date == null)
            return "";
        return dtFormatSimpleFull.format(date);
    }
    public static String currentToDateTimeSimpleFull()
    {        
        return dateToDateTimeSimpleFull(getDate());
    }
    public static String dateToInputStrAMPM(java.util.Date date)
    {
        if (date == null)
            return "";
        return timeFormatAMPM.format(date);
    }
    
    public static String dateToInputStrAMPMIncludeSeconds(java.util.Date date)
    {
        if (date == null)
            return "";
        return timeFormatAMPMIncludeSeconds.format(date);
    }
    public static String dateToInputStrAMPMNoSeconds(java.util.Date date)
    {
        if (date == null)
            return "";
        return timeFormatNoSeconds.format(date);
    }


    public static String getCurrentDay()
    {
        String dateTime = timeFormatSimple.format(getDate());
        return dateTime.substring(0,8);
    }

    public static boolean isCurrentDateBetween(Date startDate,Date endDate)
    {
        if(startDate==null)
            return false;
        if(endDate==null)
            return isCurrentDateBetween(startDate,endDate,true);
        else
            return isCurrentDateBetween(startDate,endDate,false);

    }

    /**
         * Compute the age returning an array of integers, for year, month, and day respectively.
         * <p>
         * @param  birthdate The start date to start the age computation.
         * @param  asOf      The end date for the age computation
         * @return The age in years, months, days in the 0, 1, 2 indices respectively.
         */
    public static int[] age ( Date birthdate, Date asOf ) {
            Calendar from = Calendar.getInstance();
            Calendar to = Calendar.getInstance();
            from.setTime( birthdate );
            to.setTime( asOf );

            int birthYYYY = from.get( Calendar.YEAR );
            int birthMM = from.get( Calendar.MONTH );
            int birthDD = from.get( Calendar.DAY_OF_MONTH );

            int asofYYYY = to.get( Calendar.YEAR );
            int asofMM = to.get( Calendar.MONTH );
            int asofDD = to.get( Calendar.DAY_OF_MONTH );

            int ageInYears = asofYYYY - birthYYYY;
            int ageInMonths = asofMM - birthMM;
            int ageInDays = asofDD - birthDD;

            if ( ageInDays < 0 ) {
                // Guaranteed after this single treatment, ageInDays will be >= 0.
                // i.e. ageInDays = asofDD - birthDD + daysInBirthMM.
                ageInDays += from.getActualMaximum( Calendar.DAY_OF_MONTH );
                ageInMonths--;
            }

            if ( ageInDays == to.getActualMaximum( Calendar.DAY_OF_MONTH ) ) {
                ageInDays = 0;
                ageInMonths++;
            }

            if ( ageInMonths < 0 ) {
                ageInMonths += 12;
                ageInYears--;
            }
            if ( birthYYYY < 0 && asofYYYY > 0 ) ageInYears--;

            if ( ageInYears < 0 ) {
                ageInYears = 0;
                ageInMonths = 0;
                ageInDays = 0;
            }

            int[] result = new int[3];
            result[0] = ageInYears;
            result[1] = ageInMonths;
            result[2] = ageInDays;
            return result;
        }

    /**
     * Tests the input value to ensure that a valid Date instance can be created from it.
     * Roll over dates are not allowed here and will return a false value.
     * Eg. isValidDate(2002, 10, 32) will return false.
     * <p>
     * @param  year  The year value.
     * @param  month The month value. ( 1 - 12 )
     * @param  day   The day value. ( 1 - 31 )
     * @return True if all values can be used to create a single valid Date instance.
     */
    public static boolean isValidDate ( int year, int month, int day ) {

        if ( day <= 0 || month <= 0 || year <= 0 ) return false;
        if ( month > 12 || day > 31 ) return false;

        Calendar cal = Calendar.getInstance();
        cal.set( Calendar.YEAR, year );
        cal.set( Calendar.MONTH, month - 1 );

        // Find the maximum field value possible for the day with the year and month.
        int maxDay = cal.getActualMaximum( Calendar.DAY_OF_MONTH );
        if ( day > maxDay ) return false;

        return true;
    }
    /**
     * Tests the input string to ensure that a valid Date instance can be created from it
     * according to the format provided.
     * <p>
     * @param  date   A date string.
     * @param  format Date format to conform to.
     * @return True if it conforms to the specified date format; False otherwise.
     */
    public static boolean isValidDate ( String date, String format ) {

        if ( date == null ) return false;

        try {
             parse( date, format );
        } catch ( java.text.ParseException e ) {
            return false;
        }
        return true;
    }

    /**
     * Tests the input string to ensure that a valid Date instance can be created
     * according to the date format specified in the System property.
     * <p>
     * If the properties file is not available or the dateformat property has
     * not been specified, the default format "dd/MM/yyyy" will be used.
     * <p>
     * @param  date A date string.
     * @return True if it conforms to the system date format; False otherwise.
     */
    public static boolean isValidDate ( String date ) {
        if ( date == null ) return false;

        try {
            parse( date );
        } catch ( java.text.ParseException e ) {
            return false;
        }

        return true;
    }

    /**
     * Tests if the inputs are valid time. When the ampm parameter is true,
     * the input hour will be tested for 12-hour format ( 1 ? 12 ).
     * When it is false, the input hour will be tested for 24-hour format ( 0 ? 23 ).
     * <p>
     * @param  hour   The Hour value. ( 0 - 23 or 1 - 12 )
     * @param  minute The Minute value. ( 0 - 59 )
     * @param  ampm   If true, the time is in 12 hour format.
     * Otherwise, it is in 24 hour format.
     *
     * @return True if the time inputs can be used to create a valid time instance.
     */
    public static boolean isValidTime ( int hour, int minute, boolean ampm ) {

        if ( minute < 0 || minute > 59 )
            return false;

        if ( ampm && ( hour < 1 || hour > 12 ) )
            return false;

        else if ( hour < 0 || hour > 23 )
            return false;

        else
            return true;
    }

    /**
     * Tests the input string to ensure that a valid time can be created
     * according to the time format provided.
     * <p>
     * @param  time   The time string.
     * @param  format Time format to conform to.
     * @return True if it conforms to the specified time format; False otherwise.
     */
    public static boolean isValidTime ( String time, String format ) {

        if ( time == null || format == null ) return false;

        try {
            parse( time, format );
        } catch ( java.text.ParseException e ) {
            return false;
        }

        return true;
    }

    /**
     * Returns a Date object instance from the input string.
     * The input string is parsed to return a date object based
     * on the date format specified in the System property.
     * <p>
     * @param  date The date string.
     * @return The date instance created.
     */
    public static Date parse ( String date ) throws java.text.ParseException {
        if ( date == null ) return null;

        String dateformat = "dd/MM/yyyy";
        return parse( date, dateformat );
    }

    /**
     * Returns a Date object instance from the input string.
     * The input date string is parsed to return a date object
     * based on the format provided.
     * <p>
     * Eg., to parse the date string "01/01/2003 9:2 PM", use the
     * format "dd/MM/yyyy h:m a". The resultant data object will have
     * the value "Mar 11 2003 09:02", as displayed in 24 hr format.
     * <p>
     * @param  date   The date string.
     * @param  format The date format that the date string conforms to.
     * @return The date instance created.
     * @throws java.text.ParseException  - if the beginning of the specified string cannot be parsed.
     */
    public static Date parse ( String date, String format ) throws java.text.ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat( format );
        sdf.setLenient( false );

        return sdf.parse( date );
    }

    /**
     * Returns a Date object instance from the input string.
     * This method is specifically for date string of the form "EEE MMM dd HH:mm:ss 'GMT+08:00' yyyy"
     * <p>
     * For eg, "Thu Jun 30 15:00:54 GMT+08:00 2003"
     *
     * @param date  The date string of the format "EEE MMM dd HH:mm:ss 'GMT+08:00' yyyy"
     * @return The date instance created.
     * @throws java.text.ParseException - if the date string is not of the given format.
     */
    public static Date parseLocale ( String date ) throws java.text.ParseException {

        String localeFormat = "EEE MMM dd HH:mm:ss 'GMT+08:00' yyyy";

        return parse( date, localeFormat );
    }

    public static boolean isCurrentDateBetween(Date effDt,Date expDt,boolean canExpDtNull)
    {
        if(effDt==null)
            return false;
        Date currentDate = new Date(System.currentTimeMillis());
        if(canExpDtNull&&(expDt==null))
            return currentDate.compareTo(effDt)>=0;
        else
            return ((currentDate.compareTo(effDt)>=0)&&(currentDate.compareTo(getNextDate(expDt))<=0));
    }

    public static Date getNextDate(Date date)
    {
        if(date==null)
            return null;
        Calendar cal = GregorianCalendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_YEAR,1);
        return cal.getTime();
    }

        
    /**
     * Return the Date instance with the provided year,
     * month ( 1 ? 12 ), and day ( 1 - 31 ) values.
     * <p>
     * The date value will roll over when given a value that is greater
     * than the max possible. Eg. when getDate( 2002, 10, 32 )
     * is provided, the Date instance will be 1st Nov 2002.
     * <p>
     * @param  year  Year
     * @param  month Month ( 1 - 12 )
     * @param  day   Day( 1 - 31 )
     * @return The Date instance created.
     */
    public static Date getDate ( int year, int month, int day ) {
        Calendar cal = Calendar.getInstance();

        // Clear all fields first
        cal.clear();

        cal.set( year, month - 1, day );

        return cal.getTime();
    }

 

    /**
     * Returns the date instance based on the current system date
     * <p>
     * @return Current System date.
     */
    public static Date getDate () {
        TimeZone tz = TimeZone.getTimeZone( timezone );
        return Calendar.getInstance( tz ).getTime();
    }


    /**
     * private the constructor,and invoid the new operation
     */
    private DateUtil(){
    }

    /**
     * Retrieves the value of the field in the Date.
     * Some common fields that is likely to be used include :
     * <p>
     * <li>Calendar.YEAR - retrieves the year value
     * <li>Calendar.MONTH - retrieves the month value ( 1 - 12 )
     * <li>Calendar.DAY_OF_MONTH - retrieve the day value ( 1 - 31 )
     * <li>Calendar.HOUR - retrieves the hours value in 12 hour format ( 1 - 12 )
     * <li>Calendar.HOUR_OF_DAY - retrieves the hours value in 24 hour format ( 0 - 23 )
     * <li>Calendar.MINUTE - retrieves the minutes value ( 0 - 59 )
     * <li>Calendar.AM_PM - retrieves the am/pm value ( 0 = am; 1 = pm )
     * <p>
     * @param  date  The Date object to extract value from.
     * @param  field A Calendar constant to retrieve the field value from the Date
     * object.
     * @return The value of the field that is requested.
     * @throws ArrayIndexOutOfBoundsException - if specified field is out of
     * range (<code>field</code> &lt; 0 || <code>field</code> &gt;= <code>Calendar.FIELD_COUNT</code>).
     * @see java.util.Calendar
     */
    public static int get ( Date date, int field ) {

        Calendar cal = Calendar.getInstance();

        cal.setTime( date );

        int value = cal.get( field );

        // Add 1 if the field is Calendar.MONTH since Calendar returns
        // the month value starting from 0.
        if ( Calendar.MONTH == field )
            value += 1;

        // If it is 12 am/pm, the value will be 0. Need to change it to 12 for ease of display.
        if ( Calendar.HOUR == field && value == 0 )
            value = 12;

        return value;
    }

    public static int age(Date dob){
        Calendar from = Calendar.getInstance();
        Calendar to = Calendar.getInstance();
        from.setTime(dob);
        to.setTime(new Date());
        int birthYYYY = from.get( Calendar.YEAR );
        int curYYYY = to.get( Calendar.YEAR );

        int ageInYears = curYYYY - birthYYYY;

        if (ageInYears < 0)
            ageInYears = 0;

        return ageInYears;
    }
    public static int dayBetweenTwoDates(Date beginDate, Date endDate){
        int days;
        int pnMark = 1;
        if(endDate!=null && beginDate != null)
        {
        	
            Calendar bCalendar = Calendar.getInstance();
            Calendar eCalendar = Calendar.getInstance();
            if(beginDate.after(endDate))
        	{
            	pnMark = -1;
            	bCalendar.setTime(endDate);
	            eCalendar.setTime(beginDate);
        	}else
        	{
	            bCalendar.setTime(beginDate);
	            eCalendar.setTime(endDate);
        	}
            int dayBegin = bCalendar.get(Calendar.DAY_OF_YEAR);
            int dayEnd = eCalendar.get(Calendar.DAY_OF_YEAR);
            days = dayEnd - dayBegin;
            int endYear = eCalendar.get(Calendar.YEAR);
            if(bCalendar.get(Calendar.YEAR) != endYear){
                bCalendar = (Calendar)bCalendar.clone();
            }
            while(bCalendar.get(Calendar.YEAR) != endYear)
            {
                days += bCalendar.getActualMaximum(Calendar.DAY_OF_YEAR);
                bCalendar.add(Calendar.YEAR, 1);
            };
        }else
            days = 0;

        return days*pnMark;
    }
    
	/**
	 * Convert String To Date Using "dd/MM/yyyy HH:mm" Format.
	 * 
	 * @param inputStr is a String to be converted to Date
	 *        
	 * @return
	 */
	public static java.util.Date parseTimeNoSeconds(String inputStr)
    {
		if (inputStr == null || inputStr.trim().equals("")) {
			return null;
		}
		
		Date result = null;
		try {
			result = timeFormatNoSeconds.parse(inputStr);
		} catch (Exception e) {
//			if (logger.isWarnEnabled()) {
//				logger.warn("Failed to parse datetime (date=" + inputStr
//						+ ", pattern=" + "dd/MM/yyyy HH:mm", e);
//			}
		}
			
     	return result;
    }
	/**
	 * get data format form formatter pool.
	 * 
	 * @param formatType
	 * @return SimpleDateFormat.
	 */
//	public static SimpleDateFormat getDateFormat(String formatType) {
//		SimpleDateFormat sdf = formatPool.get(formatType);
//		if (sdf == null) {
//			sdf = new SimpleDateFormat(formatType);
//			formatPool.put(formatType, sdf);
//		}
//		return sdf;
//	}
		 /**
     * Returns the corresponding 3 letter string value of the month specified by numeric month value
     *
     * @param month The numeric value of the specified month
     * @return the corresponding 3 letter string value of the month specified by numeric month value
     */
    public static String getStrMth(int month)
    {
        if(month == 1)
        {
            return MTH_JAN;
        } else if(month == 2)
        {
            return MTH_FEB;
        } else if(month == 3)
        {
            return MTH_MAR;
        } else if(month == 4)
        {
            return MTH_APR;
        } else if(month == 5)
        {
            return MTH_MAY;
        } else if(month == 6)
        {
            return MTH_JUN;
        } else if(month == 7)
        {
            return MTH_JUL;
        } else if(month == 8)
        {
            return MTH_AUG;
        } else if(month == 9)
        {
            return MTH_SEP;
        } else if(month == 10)
        {
            return MTH_OCT;
        } else if(month == 11)
        {
            return MTH_NOV;
        } else if(month == 12)
        {
            return MTH_DEC;
        } else
        {
            return "";
        }
    }
    
    
    public static Integer getIntMth(String month)
    {
    	if(month==null || month.trim().equals("")){
    		return -1;
    	}else if(month.trim().equalsIgnoreCase(MTH_JAN))
        {
            return 1;
        } else if(month.trim().equalsIgnoreCase(MTH_FEB))
        {
            return 2;
        } else if(month.trim().equalsIgnoreCase(MTH_MAR))
        {
            return 3;
        } else if(month.trim().equalsIgnoreCase(MTH_APR))
        {
            return 4;
        } else if(month.trim().equalsIgnoreCase(MTH_MAY))
        {
            return 5;
        } else if(month.trim().equalsIgnoreCase(MTH_JUN))
        {
            return 6;
        } else if(month.trim().equalsIgnoreCase(MTH_JUL))
        {
            return 7;
        } else if(month.trim().equalsIgnoreCase(MTH_AUG))
        {
            return 8;
        } else if(month.trim().equalsIgnoreCase(MTH_SEP))
        {
            return 9;
        } else if(month.trim().equalsIgnoreCase(MTH_OCT))
        {
            return 10;
        } else if(month.trim().equalsIgnoreCase(MTH_NOV))
        {
            return 11;
        } else if(month.trim().equalsIgnoreCase(MTH_DEC))
        {
            return 12;
        } else
        {
            return -1;
        }
    }
    /**
     * Returns  date format dd mmStr yyyy
     *
     * @param 
     * @return date format dd mmStr yyyy
     */
    
    public static String getDateToinputWithMonthStr(Date date)
    {
    	 SimpleDateFormat bartDateFormat =new SimpleDateFormat("yyyy");      
		 String dd=String.valueOf(date.getDate());
		 int month=date.getMonth()+1;
		 String yyyy=String.valueOf(bartDateFormat.format(date));
		 String monthStr=getStrMth(month);
		 return dd+" "+monthStr+" "+yyyy;
    }
    
    public static boolean isWeekend(Date date){
    	Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int weekNo = cal.get(Calendar.DAY_OF_WEEK);
		if(weekNo == 1 || weekNo == 7){
			return true;
		}
		return false;
    }
    

    //added by bruce start
    public static String formatDateString(String date)
    {
    	StringBuffer returnStr=new StringBuffer();
    	String[] values=date.split(" ");
    	if(values.length>1){
    		returnStr.append("'")
    		.append(values[0])
    		.append("','")
    		.append(values[1])
    		.append("'");
    	}else{
    		returnStr.append("'")
    		.append(values[0])
    		.append("','")
    		.append("00:00:00")
    		.append("'");
    	}
    	
		 return returnStr.toString();
    }
    
    public static long getHour(Date tDate, Date fDate) {

		long times = (tDate.getTime() - fDate.getTime()) / (1000*60);

		return times / 60;
	}
    
    public static long getMinute(Date tDate, Date fDate) {

		long times = (tDate.getTime() - fDate.getTime()) / (1000*60);

		return times % 60;
	}
	
	public static String getCurrentDateStr() {
		return formatDate(new Date(),yyyy_MM_dd_HH_mm_ss);
	}
	
	public static String getDateStr(Date date) {
		return formatDate(date,yyyy_MM_dd_HH_mm_ss);
	}
	
	/**
	 * Format a Date using a supplied format pattern.
	 * 
	 * @param d
	 * @param pattern
	 * @return String the formatted string.
	 */
	public static String formatDate(Date d, String pattern) {
		if (d == null)
			return null;

		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(d);
	}

}